﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossLayerCommunication
{
    public static class OperationResultExtensions
    {
        public static IOperationResult Merge(this IOperationResult operationResult, IOperationResult operationResultToMerge)
        {
            operationResult.AddMessages(operationResultToMerge.Messages.ToArray());

            return operationResult;
        }

        public static IOperationResult<T> Merge<T>(this IOperationResult<T> operationResult, IOperationResult operationResultToMerge)
        {
            operationResult.AddMessages(operationResultToMerge.Messages.ToArray());

            return operationResult;
        }

        public static IOperationResult<T> Merge<T, U>(this IOperationResult<T> operationResult, IOperationResult<U> operationResultToMerge, Action<T, U> mapperFactory) where T:class
        {
            operationResult.Merge(operationResultToMerge);

            if (mapperFactory != null)
                mapperFactory(operationResult.Data, operationResultToMerge.Data);

            return operationResult;
        }

        public static IOperationResult ReplaceMessageKeyIfMessage(this IOperationResult taskResult, IMessage message, string newKey)
        {
            var err = taskResult.Messages.FirstOrDefault(item => item.Id == message.Id);

            if (err != null)
            {                
                err.Key = newKey;                
            }

            return taskResult;
        }
    }
}
